package com.sjzd.server.config.filter;

import com.sjzd.server.exception.YebCommonException;
import com.sjzd.server.pojo.Admin;
import com.sjzd.server.pojo.Menu;
import com.sjzd.server.pojo.Role;
import com.sjzd.server.service.IMenuService;
import com.sjzd.server.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  url拦截器
 *  根据url分析出所需要的角色信息
 * @author ZFQ
 * @date 2021/3/6
 */
@Component
public class Url2RoleFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus = menuService.getMenusByRole();
        if (!menus.isEmpty()) {
            for (Menu menu : menus) {
               if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                   String[] rnames = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                   if (null != rnames) {
                       return SecurityConfig.createList(rnames);
                   }
               }
            }
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        throw new YebCommonException("服务器繁忙请重试！");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
